package com.splic.product.service.impl;

import cn.hutool.core.date.DateUtil;
import com.splic.common.core.DeviceContext;
import com.splic.common.enums.EmailCodeTypeEnum;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.EmailUtil;
import com.splic.common.utils.MathUtils;
import com.splic.common.utils.RandomCodeUtil;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.*;
import com.splic.product.dto.SendCodeDto;
import com.splic.product.service.EmailSendCodeService;
import com.splic.product.service.ProductService;
import com.splic.product.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailSendCodeServiceImpl implements EmailSendCodeService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${ruoyi.register.confirmUrl}")
    private String registerConfirmUrl;
    @Autowired
    private ProductService productServiceImpl;
    @Autowired
    private UserService userServiceImpl;

    @Override
    public boolean sendEmailCode(SendCodeDto sendCodeDto) {
        String code = "";

        User user = userServiceImpl.getUserByVague(sendCodeDto.getAccount());
        if (user == null) {
            throw new BusinessException("系统找不到这个用户账号。");
        }
        sendCodeDto.setAccount(user.getEmail());

        EmailCodeTypeEnum codeTypeEnum = EmailCodeTypeEnum.getCode(sendCodeDto.getType());

        Product product = productServiceImpl.getByPackageKey(DeviceContext.getProductPackageKey());
        if (product == null) {
            throw new BusinessException("系统找不到这个应用。");
        }
        sendCodeDto.setProductName(product.getName());


        String key = "";
        //当邮件验证时、转换账号为随机数
        if (StringUtils.equals(EmailCodeTypeEnum.EMAIL_VERIFIC.getCode(), sendCodeDto.getType())) {
            code = RandomCodeUtil.havePrefixCode("CHECK");

            key = getSendCodeRedisKey(codeTypeEnum.getCode(), code);
        } else {
            code = MathUtils.randomDigitNumber(6);
            key = getSendCodeRedisKey(codeTypeEnum.getCode(), sendCodeDto.getAccount());
        }

        try {
            String subject = "[" + sendCodeDto.getProductName() + "]" + getEmailSubject(codeTypeEnum.getCode());
            String content = getEmailContent(sendCodeDto, code);
            String resObj = this.sendEmail(sendCodeDto.getAccount(), subject, content);
            if (StringUtils.isEmpty(resObj)) {
                log.info("验证码邮件发送失败。：");
                throw new BusinessException("验证码邮件发送失败。");
            } else {
                // 验证码缓存30分钟
                if (StringUtils.equals(EmailCodeTypeEnum.EMAIL_VERIFIC.getCode(), sendCodeDto.getType())) {
//                    邮箱验证改为48小时有效
                    redisTemplate.opsForValue().set(key, sendCodeDto.getAccount(), 48, TimeUnit.HOURS);
                } else {
                    redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            log.error("验证码邮件发送失败。");
            throw new BusinessException("验证码邮件发送失败。");
        }
        return true;
    }


    @Override
    public String checkEmailRegister(String action, String random) {
        String key = getSendCodeRedisKey(action, random);
        Object tempCode = redisTemplate.opsForValue().get(key);
        if (tempCode != null) {
            return tempCode.toString();
        } else {
            throw new BusinessException("账号注册验证链接未确认或已失效");
        }
    }

    @Override
    @Async
    public void sendEmailFeedback(UserFeedback userFeedback, String productName) {
        String subject = getEmailSubject(EmailCodeTypeEnum.FEEDBACK.getCode());
        String content = getFeedbackEmailContent(userFeedback);
        String resObj = this.sendEmail("product@easyjoy.me", "[" + productName + "]" + subject + "[" + userFeedback.getId() + "]", content);
        if (StringUtils.isEmpty(resObj)) {
            log.info("发送用户反馈邮件失败:{}", userFeedback.getEmail());
        }
    }

    @Override
    @Async
    public void sendEmailSubscribe(UserSubRecord userSubRecord, User user, Order order, String goodsDesc) {
        String subject = getEmailSubject(EmailCodeTypeEnum.SUBSCRIBE.getCode());
        String content = getSubscribeEmailContent(userSubRecord, user.getNickname(), order, goodsDesc);
        String resObj = this.sendEmail(user.getEmail(), subject + "[" + userSubRecord.getProductName() + "]" + "[" + userSubRecord.getGoodsTypeName() + "]", content);
        if (StringUtils.isEmpty(resObj)) {
            log.info("发送用户反馈邮件失败:{}", order.getOrderNo());
        }
    }

    private String sendEmail(String account, String subject, String content) {
        try {
            return EmailUtil.sendEmailCode(account, subject, content);
        } catch (Exception e) {
            log.error("发送邮件验证码失败");
            e.printStackTrace();
        }
        return "";
    }

    public void checkEmailCode(String action, String account, String code) {
        String key = getSendCodeRedisKey(action, account);
        Object tempCode = redisTemplate.opsForValue().get(key);
        if (tempCode != null) {
            if (!StringUtils.equals(String.valueOf(tempCode), code)) {
                throw new BusinessException("邮箱验证码错误，请您检查。");
            }
        } else {
            throw new BusinessException("邮箱验证码已失效，请您返回重新获取。");
        }
    }


    /**
     * 删除redis库中验证码
     *
     * @param action
     * @param account
     * @return
     */
    public boolean deleteEmailCode(String action, String account) {
        String key = getSendCodeRedisKey(action, account);
        redisTemplate.delete(key);
        return true;
    }

    /**
     * 获取验证码缓存key
     *
     * @param action
     * @param account
     * @return
     */
    private String getSendCodeRedisKey(String action, String account) {
        String key = "EMAIL_CODE_" + action + "_" + account;
        return key;
    }

    private String getEmailSubject(String code) {
        if (Objects.equals(EmailCodeTypeEnum.REG.getCode(), code)) {
            return "注册邮件";
        } else if (Objects.equals(EmailCodeTypeEnum.UP_PASS.getCode(), code)) {
            return "重置密码邮件";
        } else if (Objects.equals(EmailCodeTypeEnum.EMAIL_VERIFIC.getCode(), code)) {
            return "邮箱验证邮件";
        } else if (Objects.equals(EmailCodeTypeEnum.FEEDBACK.getCode(), code)) {
            return "用户反馈邮件";
        } else if (Objects.equals(EmailCodeTypeEnum.SUBSCRIBE.getCode(), code)) {
            return "您已成功订阅";
        }
        return "";

    }

    public String getEmailContent(SendCodeDto sendCodeDto, String code) {
        if (Objects.equals(EmailCodeTypeEnum.EMAIL_VERIFIC.getCode(), sendCodeDto.getType())) {
            String url = registerConfirmUrl + "?random=" + code;
            String content = "<!doctype html>\n" +
                    "<html>\n" +
                    "<head>\n" +
                    "<meta charset=\"utf-8\">\n" +
                    "<title>闹钟-邮件</title>\n" +
                    "</head>\n" +
                    "<style type=\"text/css\">\n" +
                    "\tp{font-family: \"思源黑体 CN Normal\"}\n" +
                    ".div a{color:#fff;text-decoration: none;}\n" +
                    ".div a:hover{color:#FFFFFF}\n" +
                    ".div2 a{color:#666}\n" +
                    ".div2 a:hover{color:#0079ff}\n" +
                    ".lanxian{width: 1080px; margin-top: -20px; align-content: center;}\n" +
                    ".p1{ font-size:22px;  color:#333;  font-family:\"思源黑体 CN Normal\"; line-height: 60px;}\n" +
                    ".bg{background:url(\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/ecebc979-501d-4e5d-b4f1-251002d977d6.jpg\"); background-repeat:no-repeat; background-position: center;margin-top: -22px}\n" +
                    ".kuang{ border: #cacaca 1px solid; }\n" +
                    ".p2{ font-size:22px;  color:#333;  text-align: left; margin-left: 80px; margin-top: -16px; font-family: \"思源黑体 CN Normal\"}\n" +
                    ".p3{font-size: 20px; color: #333; text-align: left; margin-left: 80px; margin-top: -20px; line-height: 40px; font-family: \"思源黑体 CN Normal\"}\n" +
                    ".p4{font-size: 20px; color: #666; text-align: left; margin-left: 80px; line-height: 40px; margin-top: 20px;  font-family:\"思源黑体 CN Normal\"}\n" +
                    ".button{ width:300px; padding-left:50px;height:50px;  padding-right:50px;  background:#0079ff;border:none;color:#fff;border-radius; font-size: 24px; border-radius: 40px; font-family:  }\n" +
                    "#square{height: 10px;background: #0079FF}\n" +
                    "</style>\n" +
                    "<body style=\" height: 1400px;\" >\n" +
                    "<div id=\"square\">\n" +
                    "</div>\n" +
                    "<div align=\"center\">\n" +
                    "<div class=\"kuang\" style=\"width: 720px;height: 880px \" >\n" +
                    "    <div>\n" +
                    "<div align=\"center\">\n" +
                    "<div class=\"bg\">\n" +
                    "        <div class=\"p1\">\n" +
                    "<p> " + sendCodeDto.getProductName() + "</p>\n" +
                    "    </div>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "   </div>\n" +
                    "<div>\n" +
                    "        <div class=\"p2\">\n" +
                    "<p>亲爱的用户:</p>\n" +
                    "</div>\n" +
                    "<div class=\"p3\">\n" +
                    "<p>感谢您注册使用[" + sendCodeDto.getProductName() + "],请您点击以下按钮验证您的\n" +
                    "\t邮箱，验<br>证后您可以使用邮箱来找回密码。</p>\n" +
                    "</div>\n" +
                    "<div style=\"border-radius: 40px\" align=\"center\" class=\"div\">\n" +
                    "<button type=\"button\" class=\"button\" ><a href=" + url + ">立即验证</a> </button>\n" +
                    "    </div>\n" +
                    "<div class=\"p4\">\n" +
                    "\t如果以上按钮无效，请您将以下链接复制到浏览器并打开以完<br>成验证。<br>\n" +
                    "    <div class=\"div2\"><a href=" + url + " >" + url + "</a></div>本验证邮件将在30分钟后失效，请您及时验证。\n" +
                    "</div>\n" +
                    "<div>\n" +
                    "<img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/e45b5997-9c40-40b9-b1e8-4616e8a74c7b.jpg\" width=\"720px\" >\n" +
                    "    </div>\n" +
                    "<div align=\"center\">\n" +
                    "<img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/20a5cad1-a2c1-405b-936f-6b21073a29c7.jpg\"  style=\"margin-top: 20px\" width=\"400px\">\n" +
                    "<p style=\"font-size: 20px; color: #cacaca; margin-top: 10px\">打开微信二维码扫一扫关注公众号</p>\n" +
                    "</div>\n" +
                    "<div style=\"font-size: 20px; color: #999; line-height: 40px ; margin-left:80px; text-align: left\">\n" +
                    "<p>这是一封自动生成的邮件，请您不要回复。 <br>如有疑问，请您通过以下方式与我们联系：<br> 邮箱: product@easyjoy.me <br>微信公众号：EasyJoy_Press</p>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "<div align=\"center\" style=\"font-size: 18px; color: #999 ; margin-top: -10px\">\n" +
                    "    <p>安徽乐汇信息科技有限公司</p>\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "</body>\n" +
                    "</html>";

            return content;
        } else if (Objects.equals(EmailCodeTypeEnum.UP_PASS.getCode(), sendCodeDto.getType())) {
            String content = "<!doctype html>\n" +
                    "<html>\n" +
                    "<head>\n" +
                    "<meta charset=\"utf-8\">\n" +
                    "<title>闹钟-邮件</title>\n" +
                    "</head>\n" +
                    "<style type=\"text/css\">\n" +
                    "\tp{font-family: \"思源黑体 CN Normal\"}\n" +
                    ".div a{color:#fff;text-decoration: none;}\n" +
                    ".div a:hover{color:#FFFFFF}\n" +
                    ".div2 a{color:#666}\n" +
                    ".div2 a:hover{color:#0079ff}\n" +
                    ".lanxian{width: 1080px; margin-top: -20px; align-content: center;}\n" +
                    ".p1{ font-size:22px;  color:#333; line-height: 60px;  font-family:\"思源黑体 CN Normal\"}\n" +
                    ".bg{background:url(\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/3027bfbc-fafd-42b7-8000-21574abafa4a.jpg\");background-repeat:no-repeat; background-position: center; margin-top: -22px; }\n" +
                    ".kuang{ border: #cacaca 1px solid; }\n" +
                    ".p2{ font-size:22px;  color:#333;  text-align: left; margin-left: 70px; margin-top: -16px; font-family: \"思源黑体 CN Normal\"}\n" +
                    ".p3{font-size: 20px; color: #333; text-align: left; margin-left: 70px; margin-top: -20px; line-height: 40px; font-family: \"思源黑体 CN Normal\"}\n" +
                    ".p4{font-size: 20px; color: #666; text-align: left; margin-left: 70px; margin-top: -20px; line-height: 30px;  font-family:\"思源黑体 CN Normal\"}\n" +
                    ".button{ width:300px; padding-left:50px;height:50px;  padding-right:50px;  background:#0079ff;border:none;color:#fff;border-radius; font-size: 24px; border-radius: 40px;  }\n" +
                    "#square{height: 10px;background: #0079FF}\n" +
                    "\n" +
                    "</style>\n" +
                    "<body style=\" height: 1200px;\" >\n" +
                    "<div id=\"square\">\n" +
                    "\n" +
                    "</div>\n" +
                    "<div align=\"center\">\n" +
                    "\n" +
                    "<div class=\"kuang\" style=\"width: 720px;height: 500px \" >\n" +
                    "    <div>\n" +
                    "<div align=\"center\">\n" +
                    "  \n" +
                    "\n" +
                    "<div class=\"bg\">\n" +
                    "        <div class=\"p1\">\n" +
                    "<p> " + sendCodeDto.getProductName() + "</p>\n" +
                    "    </div>\n" +
                    "\n" +
                    "</div>\n" +
                    "   \n" +
                    "</div>\n" +
                    "\n" +
                    "   </div>\n" +
                    "\n" +
                    "<div>\n" +
                    "        <div class=\"p2\">\n" +
                    "<p>亲爱的用户:</p>\n" +
                    "\n" +
                    "\n" +
                    "</div>\n" +
                    "\n" +
                    "<div class=\"p3\">\n" +
                    "<p>您正在进行重置密码的操作，请您将以下验证码填入应用中并重新<br>设置密码。\n" +
                    "                     <br>验证码：" + code + "</p>\n" +
                    "\n" +
                    "\n" +
                    "</div>\n" +
                    "\n" +
                    "\n" +
                    "<div class=\"p4\">\n" +
                    "\t如果此操作并非您本人进行，请您检查您的账户，确保安全。\n" +
                    "若您<br>并没有注册[" + sendCodeDto.getProductName() + "]账号，请您忽略此邮件。<br>\n" +
                    "   \n" +
                    "</div>\n" +
                    "<div>\n" +
                    "<img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/2022/04/13/d00176e7e2cd45d08c5522104e129c1c.png\" width=\"720px\" >\n" +
                    "    </div>\n" +
                    "<div align=\"center\">\n" +
                    "   \n" +
                    "<img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/20a5cad1-a2c1-405b-936f-6b21073a29c7.jpg\"  style=\"margin-top: 20px\" width=\"400px\">\n" +
                    "<p style=\"font-size: 20px; color: #cacaca; margin-top: 10px\">打开微信二维码扫一扫关注公众号</p>\n" +
                    "\n" +
                    "</div>\n" +
                    "\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "\n" +
                    "<div align=\"center\" style=\"font-size: 18px; color: #999 ; margin-top: -10px\">\n" +
                    "    <p>安徽乐汇信息科技有限公司</p>\n" +
                    "\n" +
                    "</div>\n" +
                    "</div>\n" +
                    "</body>\n" +
                    "</html>";
            return content;
        }
        return "";
    }


    private String getFeedbackEmailContent(UserFeedback userFeedback) {
        String content = userFeedback.getContent() + "<br />\n" +
                "               手机:" + userFeedback.getMobile() + "<br />\n" +
                "               邮箱:" + userFeedback.getEmail() + "<br />\n" +
                "               QQ:" + userFeedback.getQq() + "<br />\n" +
                "               微信:" + userFeedback.getWechat() + "<br />\n";
        return content;
    }


    private String getSubscribeEmailContent(UserSubRecord userSubRecord, String nickname, Order orderNo, String goodsDesc) {
        String name = "";
        String item = "";
        try {
            String[] descArr = goodsDesc.split("：|:");
            name = descArr[0];
            item = descArr[1].replaceAll("；|;", "；<br>").replaceAll("。", "。<br>");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("服务套餐描述格式不规范");
        }
        String content = "<!doctype html>\n" +
                "<html>\n" +
                "<head>\n" +
                "    <meta charset=\"utf-8\">\n" +
                "    <title>订阅成功通知-邮件</title>\n" +
                "</head>\n" +
                "<style type=\"text/css\">\n" +
                "                    \\tp{font-family: \"思源黑体 CN Normal\"}\n" +
                "                    .div a{color:#fff;text-decoration: none;}\n" +
                "                    .div a:hover{color:#FFFFFF}\n" +
                "                    .div2 a{color:#666}\n" +
                "                    .div2 a:hover{color:#0079ff}\n" +
                "                    .lanxian{width: 1080px; margin-top: -20px; align-content: center;}\n" +
                "                    .p1{ font-size:22px;  color:#333; line-height: 60px;  font-family:\"思源黑体 CN Normal\"}\n" +
                "                    .bg{background:url(\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/upload/2022/04/07/3027bfbc-fafd-42b7-8000-21574abafa4a.jpg\");background-repeat:no-repeat; background-position: center; margin-top: -22px; }\n" +
                "                    .kuang{ border: #cacaca 1px solid; }\n" +
                "                    .p2{ font-size:24px;  color:#333;  text-align: left; margin-top: 20px; font-family: \"思源黑体 CN Normal\"}\n" +
                "                    .p3{font-size: 22px; color: #333; text-align: left; margin-bottom: -20px; line-height: 40px; font-family: \"思源黑体 CN Normal\"}\n" +
                "                    .p5{font-size: 22px; color: #333; text-align: left; margin-top: 20px; line-height: 40px; font-family: \"思源黑体 CN Normal\"}\n" +
                "                    .p4{font-size: 18px; color: #666; text-align: left; margin-top: 5px; line-height: 30px;  font-family:\"思源黑体 CN Normal\"}\n" +
                "                    .p6{font-size: 18px; color: #666; text-align: left; margin-top: 5px; line-height: 30px;  font-family:\"思源黑体 CN Normal\"}\n" +
                "                    .wechat{font-size: 20px; color: #cacaca; margin-top: 10px}\n" +
                "                    .last{font-size: 18px; color: #999 ; margin-top: 10px}\n" +
                "                    .button{ width:300px; padding-left:50px;height:50px;  padding-right:50px;  background:#0079ff;border:none;color:#fff;border-radius; font-size: 24px; border-radius: 40px;  }\n" +
                "                    #square{height: 10px;background: #0079FF}\n" +
                "\n" +
                "\n" +
                "</style>\n" +
                "<body style=\" height: 960px;\">\n" +
                "<div id=\"square\">\n" +
                "\n" +
                "</div>\n" +
                "<div align=\"center\">\n" +
                "\n" +
                "    <div class=\"kuang\" style=\"width: 720px\">\n" +
                "        <div style=\" margin-left: 60px; margin-right: 60px;\">\n" +
                "            <div class=\"p2\" style=\"text-align: left;\">\n" +
                "                <p>亲爱的" + (StringUtils.isEmpty(nickname) ? "" : "[" + nickname + "]") + "，您好！</p>\n" +
                "            </div>\n" +
                "            <div class=\"p3\" style=\"text-align: left;\">\n" +
                "                <p>您成功订阅了以下服务：\n" +
                "            </div>\n" +
                "            <div class=\"p4\" style=\"text-align: left;\">\n" +
                "                订单号：" + orderNo.getOrderNo() + "\n" +
                "            </div>\n" +
                "            <div class=\"p4\" style=\"text-align: left;\">\n" +
                "                产品名称：" + orderNo.getProductName() + "\n" +
                "            </div>\n" +
                "            <div class=\"p4\" style=\"text-align: left;\">\n" +
                "                服务名称：" + orderNo.getGoodsTypeName() + "\n" +
                "            </div>\n" +
                "            <div class=\"p4\" style=\"text-align: left;\">\n" +
                "                服务套餐：" + orderNo.getGoodsName() + "\n" +
                "            </div>\n" +
                "            <div class=\"p4\" style=\"text-align: left;\">\n" +
                (userSubRecord.getEffictHour() == null || userSubRecord.getEffictHour().isEmpty() ?
                        ("                服务有效期：" + DateUtil.formatDate(userSubRecord.getEffictStartTime()) + "至" + DateUtil.formatDate(userSubRecord.getEffictEndTime()) + "\n") :
                        ("                服务时长：" + userSubRecord.getEffictHour() + "小时\n")
                ) +
                "            </div>\n" +
                "            <div class=\"p5\" style=\"text-align: left;\">\n" +
                "                " + name + "\n" +
                "            </div>\n" +
                "            <div class=\"p6\" style=\"text-align: left;\">\n" +
                "                " + item + "\n" +
                "            </div>\n" +
                "            <div>\n" +
                "                <img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/2022/04/13/d00176e7e2cd45d08c5522104e129c1c.png\"\n" +
                "                     width=\"720px\">\n" +
                "            </div>\n" +
                "            <div align=\"center\">\n" +
                "\n" +
                "                <img src=\"https://easyjoy.oss-cn-beijing.aliyuncs.com/product/2023/02/21/801db053c1194dd286fe51be48cd5f15.png\"\n" +
                "                     style=\"margin-top: 20px\" width=\"400px\">\n" +
                "                <p class=\"wechat\">打开微信扫一扫二维码关注公众号</p>\n" +
                "\n" +
                "            </div>\n" +
                "\n" +
                "        </div>\n" +
                "    </div>\n" +
                "\n" +
                "    <div align=\"center\" class=\"last\" style=\"width:720px\">\n" +
                "        <p>如果您在使用过程中有任何问题或建议，请您通过以上公众号与我们联系。</p>\n" +
                "\n" +
                "    </div>\n" +
                "\n" +
                "    <div align=\"center\" class=\"last\" style=\"width:720px\">\n" +
                "        <p>安徽乐汇信息科技有限公司</p>\n" +
                "\n" +
                "    </div>\n" +
                "</div>\n" +
                "</body>\n" +
                "</html>";
        return content;
    }


}
